<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Document</title>
    <style>
      .error {
        outline: none;
        border-color: red;
      }
      .success {
        outline: none;
        border-color: green;
      }
    </style>
  </head>
  <body>
    <div id="app"></div>
    <template id="t1">
      <div>
        <form id="form">
          <p>
            姓名
            <!-- 数据的双向绑定 -->
            <input
              :class="{
                error:rule.username,
                success:!rule.username
              }"
              type="text"
              :value="form.username"
              @input="form.username = $event.target.value;valid(/\w{2,18}/,'username')"
            /><span v-show="!rule.username">用户名必须2-18个字符</span>
          </p>

          <p>
            邮箱
            <input
              :class="{
              error:rule.email,
              success:!rule.email
            }"
              type="text"
              @input="form.email=$event.target.value;valid(emailReg,'email')"
              :value="form.email"
            />
            <span v-show="!rule.email">邮箱格式错误</span>
          </p>
        </form>
      </div>
    </template>
    <script src="./vue.js"></script>
    <script>
      // 数据驱动视图
      const vm = new Vue({
        el: "#app",
        template: "#t1",
        data: {
          emailReg:
            /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
          form: {
            // 数据->视图
            username: "jack",
            email: "jack@qq.com",
          },
          rule: {
            username: false,
            email: false,
          },
        },
        methods: {
          valid(rule, name) {
            let r = "";
            // 自定义规则
            if (typeof rule === "function") {
              r = rule();
            } else {
              r = rule.test(this.form[name]);
            }
            this.rule[name] = r;
            return r;
          },
        },
      });
    </script>
  </body>
</html>
